/* eslint-disable camelcase */
import React, {
  useRef, useMemo, useImperativeHandle, useState, useEffect,
} from 'react';
import {
  Form,
  TextField,
  Select,
  SelectBox,
  NumberField,
} from 'choerodon-ui/pro';
import { templateStepsApi } from '@choerodon/master';
import { Icon } from 'choerodon-ui';
import { observer } from 'mobx-react-lite';
import { YamlEditor } from '@choerodon/components';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
import _ from 'lodash';
import { Record } from '@/interface';
import {
  BUILD_MAVEN,
  BUILD_NPM,
  BUILD_DOCKER,
  BUILD_UPLOADJAR,
  BUILD_GO,
  BUILD_MAVEN_PUBLISH,
  BUILD_SONARQUBE,
  BUILD_UPLOAD_CHART_CHOERODON,
  TASK_TEMPLATE,
  STEP_TEMPLATE, MAVEN_BUILD, CUSTOM_BUILD,
  MAVEN_UNIT_TEST, GO_UNIT_TEST, NODE_JS_UNIT_TEST, BUILD_PUBLISH,
} from '@/routes/app-pipeline/CONSTANTS';
import { mapping as auditMapping } from './stores/auditDataSet';
import {
  mapping as StepMapping,
  transformSubmitData as stepDataSetTransformSubmitData,
  settingConfigOptionsData,
  sonarConfigData,
  accountConfigData,
  scanTypeData,
} from './stores/stepDataSet';
import {
  handleSetSubmitDataByDeployGroupConfig,
  handleSetSubmitDataByContainerConfig,
} from '@/routes/app-center-pro/components/OpenAppCreateModal';
import { valueCheckValidate } from '@/routes/app-center-pro/components/OpenAppCreateModal/components/host-app-config/content';
import DeploymentDeployDom from './components/deployment-deploy';
import ApiTestDom from './components/api-test';
import HostDeployDom from './components/host-deploy';
import {
  mapping, triggerTypeOptionsData, transformSubmitData, transformSubmitTriggerValue,
} from './stores/buildDataSet';
import { mapping as repoConfigMapping, typeData } from './stores/customRepoConfigDataSet';
import { transformSubmitData as advancedTransformSubmitData } from '../advanced-setting/stores/advancedDataSet';
import AuditDom from './components/audit';
import ChartDeployDom from './components/chart-deploy';
import CloseModal from '../close-modal';
import { useBuildModalStore } from '@/routes/app-pipeline/routes/app-pipeline-edit/components/pipeline-modals/build-modals/stores';
import AdvancedSetting from '../advanced-setting';
import StepTitle from '../step-title';
import SideStep, { typeProps } from '../side-step';
import AddStep from './components/add-step';
import StepContent from './components/step-content';
import MavenBuildAdvancedSetting from './components/mavenBuild-advancedSetting';

import './index.less';

const prefix = 'c7ncd-buildModal-content';

const handleOk = async ({
  canWait,
  BuildDataSet,
  level,
  template,
  StepDataSet,
  advancedRef,
  handleJobAddCallback,
  type,
  appService,
  id,
  data,
  // 人工卡点dataSet
  AuditDataSet,
  // chart包dataset
  ChartDeployDataSet,
  // chart包内部组件的dataset
  DeployChartDataSet,
  // 部署组dataset
  DeploymentDeployDataSet,
  // 部署组内部组件的ref
  deployGroupRef,
  DeployGroupDataSet,
  ApiTestDataSet,
  // 主机部署
  HostDeployDataSet,
  // step为是否是添加步骤的回调
  step = false,
}: any) => {
  let res = true;
  let buildRes = true;
  // 如果是任务模板的 需要加上visibility字段
  if (template === TASK_TEMPLATE) {
    // eslint-disable-next-line no-param-reassign
    data = {
      ...data,
      visibility: true,
    };
  }
  switch (type) {
    case 'cd_audit': {
      if (AuditDataSet) {
        res = await AuditDataSet.current.validate(true);
      }
      if (BuildDataSet) {
        buildRes = await BuildDataSet.current.validate(true);
      }
      const auditData = AuditDataSet.current.toData();
      const cdAuditUserIds = auditData.cdAuditUserIds.map((x: any) => (typeof x === 'object' ? x.id : x));
      const result = {
        ...data,
        ...BuildDataSet ? transformSubmitData(BuildDataSet) : {},
        auditConfig: {
          cdAuditUserIds,
          countersigned: auditData.countersigned,
          auditUserIds: cdAuditUserIds,
        },
        completed: res && buildRes,
        id,
      };
      await handleJobAddCallback(result);
      return true;
      break;
    }
    case 'audit': {
      if (AuditDataSet) {
        res = await AuditDataSet.current.validate(true);
      }
      if (BuildDataSet) {
        buildRes = await BuildDataSet.current.validate(true);
      }
      const auditData = AuditDataSet.current.toData();
      const cdAuditUserIds = auditData.cdAuditUserIds.map((x: any) => (typeof x === 'object' ? x.id : x));
      const result = {
        ...data,
        ...BuildDataSet ? transformSubmitData(BuildDataSet) : {},
        ciAuditConfig: {
          cdAuditUserIds,
          countersigned: auditData.countersigned,
        },
        appService,
        completed: res && buildRes,
        id,
      };
      await handleJobAddCallback(result);
      return true;
      break;
    }
    case 'cd_chart_deploy': {
      const flag1 = await ChartDeployDataSet?.current.validate(true);
      const flag2 = await DeployChartDataSet?.current.validate(true);
      if (BuildDataSet) {
        buildRes = await BuildDataSet.current.validate(true);
      }
      res = flag1 && flag2 && buildRes;
      const result = {
        ...data,
        ...BuildDataSet ? transformSubmitData(BuildDataSet) : {},
        chartDeployCfg: {
          ...ChartDeployDataSet?.current.toData() || {},
          ...DeployChartDataSet?.current.toData() || {},
          appServiceDTO: BuildDataSet?.current?.get(mapping.appService.name),
          appServiceId: BuildDataSet?.current?.get(mapping.appService.name)?.id,
          version: transformSubmitTriggerValue(
            BuildDataSet?.current?.get(mapping.triggerValue.name),
          ),
        },
        completed: res,
        appService,
        id,
      };
      await handleJobAddCallback(result);
      return true;
      break;
    }
    case 'chart_deploy': {
      const flag1 = await ChartDeployDataSet.current.validate(true);
      const flag2 = await DeployChartDataSet.current.validate(true);
      if (BuildDataSet) {
        buildRes = await BuildDataSet.current.validate(true);
      }
      res = flag1 && flag2 && buildRes;
      const result = {
        ...data,
        ...BuildDataSet ? transformSubmitData(BuildDataSet) : {},
        ciChartDeployConfig: {
          ...ChartDeployDataSet.current.toData(),
          ...DeployChartDataSet.current.toData(),
        },
        completed: res,
        appService,
        id,
      };
      await handleJobAddCallback(result);
      return true;
      break;
    }
    case 'deployment_deploy': {
      const flag1 = await DeploymentDeployDataSet.current.validate(true);
      const deployGroupData = await deployGroupRef.current.handleOk();
      if (!flag1 || !deployGroupData?.flag) {
        res = false;
      }
      if (BuildDataSet) {
        buildRes = await BuildDataSet.current.validate(true);
      }
      const submitData = {
        ...data,
        ...DeployGroupDataSet.current.toData(),
      };
      const returnData = handleSetSubmitDataByDeployGroupConfig({
        appConfigData: deployGroupData.appConfig,
        submitData,
      });
      let result = handleSetSubmitDataByContainerConfig({
        resourceConfigData: deployGroupData.containerConfig,
        submitData: returnData,
      });
      result = {
        ...result,
        ...BuildDataSet ? transformSubmitData(BuildDataSet) : {},
        ciDeployDeployCfg: {
          appCode: result?.appCode,
          appName: result?.appName,
          appConfig: result?.appConfig,
          appId: result?.appId,
          containerConfig: result?.containerConfig,
          deployType: DeploymentDeployDataSet?.current?.get('deployType'),
          envId: DeploymentDeployDataSet?.current?.get('envId'),
          skipCheckPermission: DeploymentDeployDataSet?.current?.get('skipCheckPermission'),
        },
        completed: res && buildRes,
        appService,
        id,
      };
      await handleJobAddCallback(result);
      return true;
      break;
    }
    case 'api_test': {
      res = await ApiTestDataSet.current.validate(true);
      if (BuildDataSet) {
        buildRes = await BuildDataSet.current.validate(true);
      }
      const result = {
        ...data,
        ...BuildDataSet ? transformSubmitData(BuildDataSet) : {},
        startIn: ApiTestDataSet.current.get('startIn'),
        completed: res && buildRes,
        appService,
        id,
        groupType: data?.type,
        devopsCiApiTestInfoVO: {
          ...ApiTestDataSet.current.toData(),
          notifyUserIds: ApiTestDataSet.current.get('notifyUserIds')?.join(','),
          sendEmail: ApiTestDataSet.current.get('notifyWay').includes('sendEmail'),
          sendSiteMessage: ApiTestDataSet.current.get('notifyWay').includes('sendSiteMessage'),
        },
      };
      await handleJobAddCallback(result);
      return true;
      break;
    }
    case 'host_deploy': {
      const hostValidate = await HostDeployDataSet.current.validate(true);
      if (BuildDataSet) {
        buildRes = await BuildDataSet.current.validate(true);
      }
      const flag = valueCheckValidate(
        HostDeployDataSet.current.get('preCommand'),
        HostDeployDataSet.current.get('runCommand'),
        HostDeployDataSet.current.get('postCommand'),
      );
      res = flag && hostValidate;
      const result = {
        ...data,
        ...BuildDataSet ? transformSubmitData(BuildDataSet) : {},
        completed: res && buildRes,
        appService,
        id,
        groupType: data?.type,
        devopsCiHostDeployInfoVO: {
          ...HostDeployDataSet.current.toData(),
          hostId: HostDeployDataSet.current.get('hostId')?.id || HostDeployDataSet.current.get('hostId'),
          ...HostDeployDataSet.current.get('deployType') === 'update' ? {
            appId: HostDeployDataSet.current.toData()?.appName,
          } : {},
        },
      };
      await handleJobAddCallback(result);
      return true;
      break;
    }
    default: {
      if (!step) {
        if (BuildDataSet) {
          res = await BuildDataSet.current.validate(true);
        }
        let stepRes = true;
        let advancedRes = true;
        if (level === 'project' || !template || ((template === TASK_TEMPLATE) && (BuildDataSet?.current?.get('type') === MAVEN_BUILD))) {
          if (StepDataSet) {
            for (let i = 0; i < StepDataSet.records.filter((j: any) => j.status !== 'delete').length; i += 1) {
              const item = StepDataSet.records.filter((j: any) => j.status !== 'delete')[i];
              // eslint-disable-next-line no-await-in-loop
              const itemResult = await item.validate(true);
              let configFlag = true;
              if ([BUILD_MAVEN, BUILD_MAVEN_PUBLISH].includes(item?.get(StepMapping.type.name))) {
                // eslint-disable-next-line no-await-in-loop
                configFlag = await item
                  .getField(StepMapping.customRepoConfig.name).options.validate();
              }
              if (!itemResult || !configFlag) {
                stepRes = false;
                break;
              }
            }
          }
          if (advancedRef?.current) {
            if (!advancedTransformSubmitData(advancedRef?.current?.getDataSet())?.image) {
              advancedRef?.current?.getDataSet()?.current?.set('image', data.oldImage);
            }
            advancedRes = await advancedRef?.current?.getDataSet()?.current?.validate(true);
          }
        }
        const getCompleted = () => {
          if (template === STEP_TEMPLATE) {
            return res;
          }
          if (StepDataSet) {
            return res && stepRes && advancedRes && StepDataSet.getState('qualityAccessControlValidate') !== false;
          }
          return res && stepRes && advancedRes;
        };
        const result = {
          // 如果需要覆盖加上data 比如builddataset和stepdataset的update更新事件
          ...data || {},
          ...BuildDataSet ? transformSubmitData(BuildDataSet) : {},
          ...StepDataSet ? {
            devopsCiStepVOList: stepDataSetTransformSubmitData(StepDataSet),
          } : {},
          ...advancedTransformSubmitData(advancedRef?.current?.getDataSet()),
          ...template === STEP_TEMPLATE ? {
            type,
          } : {},
          groupType: data?.groupType || 'build',
          // TODO 待删
          appService,
          completed: getCompleted(),
          id,
        };
        if (canWait) {
          if (template !== STEP_TEMPLATE ? res && stepRes && advancedRes : res) {
            const flag = await handleJobAddCallback(result);
            return flag;
          }
          return false;
        }
        await handleJobAddCallback(result);
        return true;
      }
      break;
    }
  }
  return false;
};

const Index = observer(() => {
  const {
    modal,
    BuildDataSet,
    StepDataSet,
    AuditDataSet,
    handleJobAddCallback,
    data,
    data: {
      id,
      type,
      // TODO 待删
      appService,
      template,
      groupType,
      configuration,
    },
    level,
    advancedRef,
    ChartDeployDataSet,
    DeployChartDataSet,
    buildModalUseStore,
    appServiceId,
    appServiceName,
    projectId,
    DeploymentDeployDataSet,
    DeployGroupDataSet,
    stageData,
    stageIndex,
    jobIndex,
    ApiTestDataSet,
    HostDeployDataSet,
    hostGroupDeploy,
    deployPayloadTypeName,
  } = useBuildModalStore();

  const contentRef = useRef<any>();

  const deployGroupRef = useRef();

  useEffect(() => {
    function handleClickOutside(event: any) {
      if (!template
        && contentRef.current
        && !contentRef.current.contains(event.target)
        && !document?.querySelector('.c7n-pro-popup-container')?.contains(event.target)
        && !document?.querySelector('.ReactModalPortal')?.contains(event.target)
      ) {
        const doms = [
          document.querySelectorAll('.c7n-menu-submenu-popup'),
          document.querySelectorAll('.c7n-pro-popup-container'),
          document.querySelectorAll('.c7n-pro-modal-container-pristine'),
          document.querySelectorAll('.c7n-pro-mask'),
          document.querySelectorAll('.c7ncd-pipeline-create-value'),
        ];
        let flag = false;
        doms.forEach((item: any) => {
          item?.length > 0 && item.forEach((d: any) => {
            if (d?.contains(event.target)) {
              flag = true;
            }
          });
        });
        if (!flag) {
          handleOk({
            canWait: false,
            BuildDataSet,
            level,
            template,
            StepDataSet,
            advancedRef,
            handleJobAddCallback,
            type,
            id,
            appService,
            data,
            AuditDataSet,
            ChartDeployDataSet,
            DeployChartDataSet,
            DeploymentDeployDataSet,
            deployGroupRef,
            DeployGroupDataSet,
            ApiTestDataSet,
            HostDeployDataSet,
          });
          modal?.close();
        }
      }
    }

    document.addEventListener('mousedown', handleClickOutside);

    return () => {
      // Unbind the event listener on clean up
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [contentRef]);

  useEffect(() => {
    handleSetScriptWhenTask();
  }, []);

  // 任务模板初始化script内容
  const handleSetScriptWhenTask = () => {
    const script = `
    # job模板，使用时根据需求替换
# job名称（与任务名称保持一致）
job_1:
  # job所属阶段名称，与创建阶段时保持一致
  stage: 构建
  # job执行内容
  script:
    - echo "hello world!"
  # 执行job的必须条件
  only:
    refs:
      - master
  # 不执行job的条件
  except:
    refs:
      - tags
# 详细定义，请参考：https://docs.gitlab.com/ee/ci/yaml/README.html
    `;
    if (template === 'task' && !data.script) {
      data.script = script;
    }
  };

  // 这里是全部展开和收起的变量
  const [expand, setExpand] = useState(true);

  const stepData = StepDataSet.data;

  const disabled = useMemo(() => (level !== 'project' || window.location.href.includes('project-pipeline-template'))
  && !template
  && !data?.type.includes('cd_'), []);

  const renderCloseModal = () => {
    if (!template) {
      return (
        <CloseModal
          preCheck={() => handleOk({
            canWait: false,
            BuildDataSet,
            level,
            template,
            StepDataSet,
            advancedRef,
            handleJobAddCallback,
            type,
            id,
            appService,
            data,
            AuditDataSet,
            ChartDeployDataSet,
            DeployChartDataSet,
            DeploymentDeployDataSet,
            deployGroupRef,
            DeployGroupDataSet,
            ApiTestDataSet,
            HostDeployDataSet,
          })}
          modal={modal}
        />
      );
    }
    return '';
  };

  const renderBuild = (ds: any, temp: string) => {
    switch (type) {
      case 'cd_audit': {
        return (
          <>
            <Form
              className={`${prefix}__main__public`}
              dataSet={BuildDataSet}
            >
              <TextField
                colSpan={5}
                name={mapping.name.name}
              />
            </Form>
            <AuditDom
              ds={AuditDataSet}
              type={type}
            />
          </>
        );
        break;
      }
      case 'cd_chart_deploy': {
        return (
          <>
            <Form
              className={`${prefix}__main__public`}
              dataSet={BuildDataSet}
              columns={2}
            >
              <TextField
                colSpan={1}
                name={mapping.name.name}
              />
              <Select searchable searchMatcher="name" name={mapping.appService.name} colSpan={1} />
              <Select
                combo
                name={mapping.triggerValue.name}
                colSpan={1}
              />
            </Form>
            <ChartDeployDom
              ds={ChartDeployDataSet}
              DeployChartDataSet={DeployChartDataSet}
              ADDCDTaskUseStore={buildModalUseStore}
              appServiceName={appServiceName
                || BuildDataSet.current?.get(mapping.appService.name)?.name}
              appServiceId={appServiceId || BuildDataSet.current?.get(mapping.appService.name)?.id}
              projectId={projectId}
              type={type}
            />
          </>
        );
        break;
      }
      default: {
        switch (temp) {
          case TASK_TEMPLATE: {
            return (
              <>
                <Form
                  columns={16}
                  disabled={disabled}
                  className={`${prefix}__main__public`}
                  dataSet={BuildDataSet}
                >
                  <TextField
                    colSpan={5}
                    name={mapping.name.name}
                  />
                  <Select colSpan={5} name={mapping.groupId.name} />
                  {
                  // 原cd任务不需要
                  !['audit',
                    'host_deploy',
                    'chart_deploy',
                    'deployment_deploy',
                    'api_test'].includes(ds?.current?.toData()?.type) ? (
                      <SelectBox colSpan={6} name={mapping.type.name} />
                    ) : ''
                }

                </Form>
                <Form
                  columns={8}
                  disabled={disabled}
                  className={`${prefix}__main__public`}
                  dataSet={BuildDataSet}
                >
                  <Select name={mapping.triggerType.name} colSpan={4} />
                  {renderTriggerValue(BuildDataSet)}
                </Form>
              </>
            );
            break;
          }
          case STEP_TEMPLATE: {
            return (
              <Form
                disabled={disabled}
                className={`${prefix}__main__public`}
                dataSet={BuildDataSet}
                columns={6}
              >
                <TextField colSpan={3} name={mapping.name.name} />
                <Select colSpan={3} name={mapping.categoryId.name} />
              </Form>

            );
            break;
          }
          default: {
            return (
              <Form
                className={`${prefix}__main__public`}
                dataSet={BuildDataSet}
                columns={6}
                disabled={disabled}
              >
                <TextField
                  colSpan={3}
                  name={mapping.name.name}
                  onInput={(e: any) => {
                    // 这里是因为在输入中直接点击其他地方关闭弹框 数据还没设置进去 数据没有保存 这里直接先保存
                    BuildDataSet.current?.set(mapping.name.name, e.target.value);
                  }}
                />
                <Select name={mapping.appService.name} colSpan={3} />
                <Select name={mapping.triggerType.name} colSpan={2} />
                {renderTriggerValue(BuildDataSet)}
              </Form>

            );
          }
        }
      }
    }
  };

  const getStepMain = (singleMode = false) => (
    [BUILD_UPLOAD_CHART_CHOERODON, BUILD_PUBLISH]
      .includes(data.stepTempType) ? ''
      : (
        <>
          <StepTitle
            className={`${prefix}__main__step`}
            title="步骤配置"
            buttons={!singleMode ? [{
              text: expand ? '全部收起' : '全部展开',
              icon: expand ? 'vertical_align_bottom' : 'vertical_align_top',
              onClick: () => handleExpand(!expand),
            }, {
              custom: true,
              dom: disabled ? '' : (
                <AddStep
                  okProps={{
                    level,
                    template,
                    advancedRef,
                    handleJobAddCallback,
                    type,
                    appService,
                    id,
                    data,
                  }}
                  template={template}
                  level={level}
                  ds={StepDataSet}
                  configuration={configuration}
                />
              ),
              // text: '添加步骤',
              // onClick: handleAddStep,
              // overlay: addStepMenu,
            }] : []}
          />
          <StepContent
            stepData={stepData}
            disabled={disabled}
            template={template}
            prefix={prefix}
            dataSet={StepDataSet}
            okProps={{
              level,
              template,
              advancedRef,
              handleJobAddCallback,
              type,
              appService,
              id,
              data,
            }}
            singleMode={singleMode}
          />
        </>
      )
  );

  const renderMain = () => {
    switch (BuildDataSet?.current?.get(mapping.type.name)) {
      case MAVEN_BUILD: {
        return (
          <>
            {getStepMain()}
            <div
              style={{
                marginTop: stepData.length > 0 ? 0 : 20,
              }}
              className={`${prefix}__main__divided`}
            />
            <AdvancedSetting
              disabled={disabled}
              data={data}
              cRef={advancedRef}
              className={`${prefix}__main__advanced`}
              BuildDataSet={BuildDataSet}
            />
          </>
        );
        break;
      }
      case CUSTOM_BUILD: {
        if (data.stepTempType === 'custom' || !data.stepTempType) {
          return (
            <>
              <StepTitle
                className={`${prefix}__main__step`}
                title="自定义脚本"
              />
              <div
                style={{
                  marginTop: 16,
                }}
              >
                <YamlEditor
                  showError={false}
                  readOnly={disabled}
                  modeChange={false}
                  value={BuildDataSet?.current?.get(mapping.script.name)}
                  onValueChange={(value: string) => BuildDataSet
                    ?.current?.set(mapping.script.name, value)}
                />
              </div>
            </>
          );
        }
        return getStepMain(true);
        break;
      }
      case 'audit': {
        return (
          <>
            <AuditDom
              ds={AuditDataSet}
            />
            <div style={{ marginTop: 20 }} className="c7ncd-addCDTask-deployChart__divided" />
            <AdvancedSetting
              disabled={disabled}
              data={data}
              cRef={advancedRef}
              className={`${prefix}__main__advanced`}
              BuildDataSet={BuildDataSet}
              isOriginCD
            />
          </>

        );
      }
      case 'chart_deploy': {
        return (
          <>
            <ChartDeployDom
              ds={ChartDeployDataSet}
              DeployChartDataSet={DeployChartDataSet}
              ADDCDTaskUseStore={buildModalUseStore}
              appServiceName={appServiceName}
              appServiceId={appServiceId}
              projectId={projectId}
            />
            <div style={{ marginTop: 20 }} className="c7ncd-addCDTask-deployChart__divided" />
            <AdvancedSetting
              disabled={disabled}
              data={data}
              cRef={advancedRef}
              className={`${prefix}__main__advanced`}
              BuildDataSet={BuildDataSet}
              isOriginCD
            />
          </>

        );
      }
      case 'deployment_deploy': {
        return (
          <>
            <DeploymentDeployDom
              detailData={data?.ciDeployDeployCfg}
              ds={DeploymentDeployDataSet}
              DeployGroupDataSet={DeployGroupDataSet}
              stageData={stageData}
              stageIndex={stageIndex}
              jobIndex={jobIndex}
              deployGroupRef={deployGroupRef}
              disabled={level !== 'project' || window.location.href.includes('project-pipeline-template')}
            />
            <div style={{ marginTop: 20 }} className="c7ncd-addCDTask-deployChart__divided" />
            <AdvancedSetting
              disabled={disabled}
              data={data}
              cRef={advancedRef}
              className={`${prefix}__main__advanced`}
              BuildDataSet={BuildDataSet}
              isOriginCD
            />
          </>

        );
      }
      case 'host_deploy': {
        return (
          <>
            <HostDeployDom
              ds={HostDeployDataSet}
              hostGroupDeploy={hostGroupDeploy}
              deployPayloadTypeName={deployPayloadTypeName}
              stageData={stageData}
              level={level}
            />
            <div style={{ marginTop: 20 }} className="c7ncd-addCDTask-deployChart__divided" />
            <AdvancedSetting
              disabled={disabled}
              data={data}
              cRef={advancedRef}
              className={`${prefix}__main__advanced`}
              BuildDataSet={BuildDataSet}
              isOriginCD
            />
          </>
        );
      }
      case 'api_test': {
        return (
          <>
            <ApiTestDom
              ds={ApiTestDataSet}
            />
            <div style={{ marginTop: 20 }} className="c7ncd-addCDTask-deployChart__divided" />
            <AdvancedSetting
              disabled={disabled}
              data={data}
              cRef={advancedRef}
              className={`${prefix}__main__advanced`}
              BuildDataSet={BuildDataSet}
              isOriginCD
            />
          </>

        );
      }
      default: {
        return '';
        break;
      }
    }
  };

  if (modal) {
    modal.handleOk(() => handleOk({
      canWait: true,
      BuildDataSet,
      level,
      template,
      StepDataSet,
      advancedRef,
      handleJobAddCallback,
      type,
      appService,
      id,
      AuditDataSet,
      ChartDeployDataSet,
      DeployChartDataSet,
      DeploymentDeployDataSet,
      deployGroupRef,
      DeployGroupDataSet,
      ApiTestDataSet,
      HostDeployDataSet,
    }));
  }

  const handleExpand = (value: boolean) => {
    stepData.forEach((record: Record) => {
      record.set(StepMapping.expand.name, value);
    });
    setExpand(value);
  };

  const renderTriggerValue = (ds: any) => {
    if (ds.current?.get(mapping.triggerType.name) === triggerTypeOptionsData[1].value) {
      return <TextField name={mapping.triggerValue.name} colSpan={4} />;
    }
    return <Select combo name={mapping.triggerValue.name} colSpan={4} />;
  };

  const handleAddStep = async () => {
    const res = await templateStepsApi.getTemplateSteps(1);
  };

  const getSiderText = () => {
    const isCUSTOM_BUILD = BuildDataSet?.current?.get(mapping.type.name) === CUSTOM_BUILD;
    const isMAVEN_BUILD = BuildDataSet?.current?.get(mapping.type.name) === MAVEN_BUILD;

    if (isMAVEN_BUILD) {
      return '步骤配置';
    }

    if (isCUSTOM_BUILD) {
      if (!data.stepTempType) { // 创建
        return '自定义脚本';
      }
      if ([BUILD_UPLOAD_CHART_CHOERODON, BUILD_PUBLISH].includes(data.stepTempType)) {
        return '';
      }
      return '步骤配置';
    }

    return '';
  };

  const getSideStepData = () => [
    {
      text: '基础配置',
      el: '.c7ncd-buildModal-content__main',
      type: 'scrollTop' as typeProps,
      display: true,
    }, {
      text: getSiderText(),
      el: '.c7ncd-buildModal-content__main__step',
      display: [MAVEN_BUILD, CUSTOM_BUILD]
        .includes(BuildDataSet?.current?.get(mapping.type.name)),
    }, {
      text: '高级设置',
      el: '.c7ncd-buildModal-content__main__advanced',
      display: [MAVEN_BUILD].includes(BuildDataSet?.current?.get(mapping.type.name)),
    }, {
      text: '应用信息',
      el: '.deployChartAppInfo',
      display: BuildDataSet?.current?.get(mapping.type.name) === 'chart_deploy',
    }, {
      text: '应用配置',
      el: '.deployChartAppConfig',
      display: BuildDataSet?.current?.get(mapping.type.name) === 'chart_deploy',
    }, {
      text: '应用信息',
      el: '.deployGroupAppInfo',
      display: BuildDataSet?.current?.get(mapping.type.name) === 'deployment_deploy',
    }, {
      text: '应用配置',
      el: '.deployGroupAppConfig',
      display: BuildDataSet?.current?.get(mapping.type.name) === 'deployment_deploy',
    }, {
      text: '容器配置',
      el: '.deployGroupContainerConfig',
      display: BuildDataSet?.current?.get(mapping.type.name) === 'deployment_deploy',
    }, {
      text: '高级设置',
      el: '.c7ncd-buildModal-content__main__advanced',
      display: [
        'chart_deploy',
        'deployment_deploy',
        'audit',
        'host_deploy', 'api_test'].includes(BuildDataSet?.current?.get(mapping.type.name)),
    },
  ];

  return (
    <div ref={contentRef} className={prefix}>
      {renderCloseModal()}
      <SideStep
        scrollContext=".c7ncd-buildModal-content__main"
        data={getSideStepData()}
      />
      <div className={`${prefix}__main`}>
        {
          renderBuild(BuildDataSet, template)
        }
        {/* <Form
          disabled={disabled}
          className={`${prefix}__main__public`}
          dataSet={BuildDataSet}
          columns={6}
        /> */}
        {
          [MAVEN_BUILD, CUSTOM_BUILD]
            .includes(BuildDataSet?.current?.get(mapping.type.name)) && (
            <div className={`${prefix}__main__divided`} />
          )
        }
        {
          renderMain()
        }
      </div>
    </div>
  );
});

export default Index;

export {
  handleOk,
};
